// import Request from "../xhr";
import Request from "../axios";
import pLimit from "p-limit";
const limit = pLimit(10);
function stringToUint8Array(str, encoding = 'utf-8') {
    if (encoding.toLowerCase() === 'utf-8') {
        const utf8 = unescape(encodeURIComponent(str))
        const arr = new Uint8Array(utf8.length)
        for (let i = 0; i < utf8.length; i++) {
            arr[i] = utf8.charCodeAt(i)
        }
        return arr
    } else {
        throw new Error('Unsupported encoding')
    }
}
class Download {
    async DownloadFile(filename: string, fileSize: number, chunkSize?: number) {
        chunkSize ||= Math.ceil(fileSize / 5)
        let start = 0
        const RangeList: any[] = []
        while (start < fileSize - 1) {
            const end = Math.min(start + chunkSize - 1, fileSize - 1)
            RangeList.push(`${start}-${end}`)
            start = end + 1
        }
        const buffer = new Array<Uint8Array>(RangeList.length)
        const requestList = RangeList.map((range, index) => limit(() => {
            return Request.get({
                url: `/download/chunk?filename=${filename}`,
                headers: {
                    'Range': range
                },
                timeout: 10000000,
                responseType: 'arraybuffer',
            }
            ).then(res => { buffer[index] = new Uint8Array(res) })
        }))
        await Promise.all(requestList)
        const results = await Promise.allSettled(requestList)
        const failedRequests = results.filter((result) => result.status === 'rejected')
        if (failedRequests.length > 0) {
            throw new Error(`部分文件块下载失败: ${failedRequests.length} 个`)
        }
        const blob = new Blob(buffer, { type: 'application/octet-stream' })
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.setAttribute('download', filename)
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
    }
}
const Downloader = new Download()
export default Downloader
